/**
 * Created by cuihongquan on 2015/7/7.
 * based on jquery.ui.js, JSpinyin.js
 */
(function (w,$) {
    $.widget('summer.region', {
        version: '1.0',
        options: {
            listUrl: null, // 第一次列表Url
            width:700,	//窗口宽度
            height:450,	//窗口高度
            rootId:'',	//根节点
            level:1,	//需要拼音分组的层级
            onselect:null
        },

        //构造dom，绑定事件
        _create: function () {
            var that = this;
            that._createRegion(that);
            that._bindEvent(that);
        },
        //初始化插件
        _init: function () {
            this._requestData(this.options.rootId);

        },
        //设置值
        setValue: function (id, infoUrl) {
        	var that = this,
        		ele = that.element,
        		eleId = ele.attr('id') ;
        	$.ajax({
                url: infoUrl || basePath+'/sys/inner/regionInfo' ,
                data:{
                    'id':id
                },
                type: 'POST',
                dataType: 'json',
                async: true,
                success: function (data) {
                    if (data.result == 'success') {
                    	$('#'+eleId+'-hidden').val(id);
                		ele.val(data.data.name);
                    }
                }
            });
        },
        //拿取行政区划
        getValue:function(){
            this._getValues(false);
        },
        //拿到行政区划从根节点开始
        getValues: function () {
            this._getValues(true);
        },
        //销毁
        destory: function () {
            this._unbindEvent();
        },
        //拿到行政区划从根节点开始
        _getValues:function(flag){
            var $win = $('#' + this.element.attr('id') + 'Container');
            if(flag){
                return $win.find('.summer-xzqh-position .summer-xzqh-position-item');
            }else{
                return $win.find('.summer-xzqh-position .summer-xzqh-position-item').eq(-1);
            }

        },
        //构建region
        _createRegion: function (that) {
            var ele = that.element, id = ele.attr('id');
            //构建input隐藏域
            ele.after('<input type="hidden" id="' + id + '-hidden" value="" name="' + ele.attr('name') + '">');
            //修改当前的input属性值
            ele.removeAttr('name');
            //构建window窗口里面的容器
            var $win = $('#' + id + 'Container');
            if ($win.length == 0) $(ele).closest('body').append('<div id="' + id + 'Container"></div>');
            $win = $('#' + id + 'Container');
            $win.append(
                //遮罩层
                    '<div class="summer-window-mask" style="display: none"></div>'+
                    //主容器
                    '<div class="summer-window-container" style="width:'+that.options.width+'px;height:' +
                    that.options.height+'px;left:50%;top:50%;margin-left:-'+that.options.width/2+'px;' +
                    'margin-top:-'+that.options.height/2+'px;z-index:9999999">'+
                    //容器头
                    '<div class="summer-window-header"><div class="summer-window-title"><i class="fa fa-laptop"></i>' +
                    '行政区划</div><a class="summer-window-close" href="javascript:;"><i class="icon icon-wrong"></i></a></div>'+
                    //容器内容
                    '<div class="summer-window-body" style="width: 100%;height: 90%;">' +
                    //行政区划容器
                    '<div class="summer-xzqh">' +
                    '<div class="summer-xzqh-nav">' +
                    '<span style="padding-left: 10px;">' +
                    '当前位置：<span class="summer-xzqh-position"></span>' +
                    '</span>' +
                    '<input type="hidden" class="summer-xzqh-data">' +
                    '</div>' +
                    //内容容器
                    '<div class="summer-xzqh-content"></div>' +
                    //添加按钮
                    '<div class="summer-xzqh-plus">' +
                    '<a class="btn btn-primary btn-large" href="javascript:;">' +
                    '<span class="btn-i">' +
                    '<i class="icon icon-plus icon-white"></i>' +
                    '</span><span class="btn-word">添加</span>' +
                    '</a></div></div></div>'
            );
        },

        //数据的请求
        _requestData: function (rootId) {
            var that = this;
            $.ajax({
                url: that.options.listUrl || basePath + '/sys/out/getStdRegionData',
                data:{
                    'id':rootId
                },
                type: 'POST',
                dataType: 'json',
                async: true,
                success: function (data) {
                    if (data.result == 'success') {
                        //构建行政区划名称
                        var root = data.data[0];
                        that._createPlace(root);
                        that._createNav(root);
                    }
                }
            });
        },

        //构建导航栏
        _createNav:function(root){
            //寻找根节点
            $('#' + this.element.attr('id') + 'Container').find('.summer-xzqh-position').append('<a href="javascript:;"'+
            		'class="summer-xzqh-position-item" data-id="'+root.id+'" data-pId="' + root.parentId + '" data-type="' + root.attributes.type+ '" data-code="'+root.attributes.code+'">'+root.text+'<span class="summer-xzqh-position-item-i"></span></a>');
        },

        //构建行政区划省市县
        _createPlace:function(node){
            var that = this, en = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                'Y', 'Z' ], $win = $('#' + that.element.attr('id') + 'Container'), content = '',region=[];
            //行政区划码
            if (node.attributes.level <= that.options.level) {
                region = that._divide(node.children, function(item) {
                    if (item.text.indexOf('重庆') != -1) {
                        return 'CQ';
                    }
                    return null;
                });
                $.each(en, function (index, value) {
                    var item = region[index];
                    if (item) {
                        content += '<div class="summer-xzqh-content-block"><div class="summer-xzqh-content-index">'
                            + value
                            + '</div><div class="summer-xzqh-content-place">';
                        $.each(item, function (i, v) {
                            content += '<a href="javascript:;" class="summer-xzqh-content-cell" data-id="'+ v.id
                                + '" data-pId="' + v.parentId + '" data-type="' + v.attributes.type+ '" data-code="'+v.attributes.code+'">'
                                + v.text + '</a>';
                        });
                        content += '</div></div>';
                    }
                });
            }else{
                region = node.children.concat();
                content += '<div class="summer-xzqh-content-block">';
                $.each(region,function(i,v){
                    content += '<a href="javascript:;" class="summer-xzqh-content-cell" data-id="'+ v.id
                        + '" data-pId="' + v.parentId + '" data-type="' + v.attributes.type+ '" data-code="'+v.attributes.code+'">'
                        + v.text + '</a>';
                });
                content += '</div>';
            }
            $win.find('.summer-xzqh-content').empty().append(content);
        },
        
        //绑定事件
        _bindEvent: function (that) {
            var ele = that.element,
                id = ele.attr('id'),
                $win = $('#' + id + 'Container');
            //绑定input的点击事件
            ele.on('click', null, function () {
                that._showWin($win);
            });
            //绑定win上关闭按钮
            $win.find('.summer-window-close').on('click',function(){
                that._closeWin($win);
            });
            //绑定nav点击事件
            $win.find('.summer-xzqh-position').on('click','.summer-xzqh-position-item',function(){
                //删除包括自己在内的后面所有节点
                $(this).nextAll('.summer-xzqh-position-item').remove();
                $(this).remove();
                that._requestData($(this).attr('data-id'));
            });
            //绑定行政区划名称点击事件
            $win.find('.summer-xzqh-content').on('click','.summer-xzqh-content-cell',function(){
                that._requestData($(this).attr('data-id'));
            });
            //绑定添加事件
            $win.find('.btn').on('click',null,function(){
                var matches = $win.find('.summer-xzqh-position .summer-xzqh-position-item'),$region = matches.eq(-1);
                that._reloadWin();
                $('#'+id +'-hidden').val($region.attr('data-id'));
                ele.val($region.text());
                that.options.onselect.call(that,$region);
                that._closeWin($win);
            });
        },
        //重置方法
        _reloadWin:function(){
            var that = this,
                ele = this.element,
                id = ele.attr('id'),
                $win = $('#' + id + 'Container'),
                $po = $win.find('.summer-xzqh-position .summer-xzqh-position-item');
            that._requestData($po.attr('data-id'));
            $po.remove();
            ele.val('');
            $('#'+id + '-hidden').val();
        },
        //窗口关闭事件
        _closeWin:function($win){
            $win.find('.summer-window-mask').hide();
            $win.find('.summer-window-container').removeClass('transition-in');
        },
        //窗口关闭事件
        _showWin:function($win){
            $win.find('.summer-window-mask').show();
            $win.find('.summer-window-container').addClass('transition-in');
        },
        //解除绑定
        _unbindEvent:function(){
            var ele = this.element,
                id = ele.attr('id'),
                $win = $('#' + id + 'Container');
            ele.off();
            $win.find('.summer-window-close').off();
            $win.find('.summer-xzqh-position').off();
            $win.find('.summer-xzqh-content').off();
            $win.find('.btn').off();
            $('#'+id+'hidden').remove();
            $win.remove();
        },
        // 将省份按照字母表分组
        _divide: function (data, doPolyphone) {
            var item = {}, //
                code = '', // 拼音简写
                asc = '', // 首字母的ascii值
                result = [];
            for (var i = 0, length = data.length; i < length; i++) {
                item = data[i];
                code = sPinYin.getCamelChars(item.text);
                // 处理多音字
                if (doPolyphone) {
                    code = doPolyphone(item) || code;
                }
                asc = code.charCodeAt(0);
                result[asc - 65] = result[asc - 65] || [];
                result[asc - 65].push(item);
            }
            return result;
        }
    });
})(window,jQuery);